<?php

if ( isset($_GET) && isset($_GET['item']) ) {
  $item = $_GET['item'];
}
else {
  die("Required parameter \"item\" missing.");
}

if ( $item == 'uptime' ) {

  $fh = fopen("/proc/uptime", "r");
  $timeStr = fgets($fh);
  fclose($fh);

  $spacePos = strpos($timeStr, " ");
  $upSecs = floatval( substr($timeStr, 0, $spacePos) );

  if ($upSecs > 86400) {
    $upDays = floor($upSecs / 86400);
    echo "$upDays day" . (($upDays > 1) ? "s" : "");
  }
  else if ($upSecs > 3600) {
    $upHr = floor($upSecs / 3600);
    echo "$upHr hour" . (($upHr > 1) ? "s" : "");
  }
  else if ($upSecs > 60) {
    $upMins = floor($upSecs / 60);
    echo "$upMins minute" . (($upMins > 1) ? "s" : "");
  }
  else {
    echo "< 1 minute";
  }

}
else if ( $item == 'df' ) {

  $outdf = array();
  exec("LC_ALL=C /bin/df -P -h /mnt/Storage/", $outdf);

  $m = array();
  if ((count($outdf) == 2) && preg_match( '/([0-9.]+[kKMGTPEZY]B?)\s+([0-9.]+[kKMGTPEZY]B?)\s+([0-9.]+[kKMGTPEZY]B?)\s+([0-9]{1,3})%\s+[^\s]+$/', $outdf[1], $m )) {
    $df_size = $m[1];  // string with unit
    $df_used = $m[2];  // "
    $df_free = $m[3];  // "
    $df_puse = intval($m[4]);
    $df_pfre = 100 - $df_puse;
    echo "${df_free} (${df_pfre}%)";
  }
  else {
    echo 'n.a.';
  }

}
else {
  die("Unknown item value: \"$item\"");
}

?>
